"""Shared utility functions for data processing"""

import json
import os
from datetime import datetime
from typing import Dict, Any

from UAS.exceptions import FileError, DataError

def load_results_file(filename: str) -> Dict[str, Any]:
    """Load JSON results file from results directory"""
    filepath = os.path.join('results', filename)
    if not os.path.exists(filepath):
        raise FileError(f"Results file not found: {filepath}")
        
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        raise DataError(f"Invalid JSON in results file: {filepath}") from e
    except Exception as e:
        raise FileError(f"Error reading results file: {filepath}") from e

def format_time(total_time: float) -> str:
    """Format total time with one decimal place"""
    return f"{total_time:.1f}"

def format_timestamp(iso_timestamp: str) -> str:
    """Format ISO timestamp to HH:MM format"""
    dt = datetime.fromisoformat(iso_timestamp)
    return dt.strftime('%H:%M')

def get_iteration_number(filename: str) -> int:
    """Extract iteration number from results filename"""
    if filename == 'results_final.json':
        # Get all result files
        result_files = [
            f for f in os.listdir('results') 
            if f.startswith('results_') and f.endswith('.json')
        ]
        # Extract numeric files and sort
        numeric_files = [
            f for f in result_files 
            if f.split('_')[1].split('.')[0].isdigit()
        ]
        if numeric_files:
            return max(
                int(f.split('_')[1].split('.')[0]) for f in numeric_files
            ) + 1
        return 1
    else:
        return int(str(filename).split('_')[1].split('.')[0])
